package com.agritech.service.impl;

import com.agritech.entity.User;
import com.agritech.mapper.UserMapper;
import com.agritech.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean register(User user) {
        // 检查用户名是否已存在
        User existingUser = userMapper.selectByUsername(user.getUsername());
        if (existingUser != null) {
            System.out.println(user.getUsername()+"用户名已存在");
            return false;
        }
        // 加密密码
        user.setPassword(user.getPassword());

        // 设置创建时间和更新时间
        Date now = new Date();
        user.setCreateTime(now);
        user.setUpdateTime(now);

        // 插入新用户
        int result = userMapper.insert(user);
        return result > 0;
    }

    @Override
    public User login(String username, String password) {
        // 查询用户
        User user = userMapper.selectByUsername(username);

        // 验证密码
        if (user != null && user.getPassword().equals(password)) {
            System.out.println("用户名："+user.getUsername()+"密码："+user.getPassword());
            return user;
        }
        return null;
    }

    @Override
    public User getById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.selectAll();
    }

    @Override
    public boolean updateUser(User user) {
        // 如果密码不为空，则加密更新
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(encryptPassword(user.getPassword()));
        }

        // 设置更新时间
        user.setUpdateTime(new Date());

        int result = userMapper.update(user);
        return result > 0;
    }

    @Override
    public boolean deleteUser(Long id) {
        int result = userMapper.delete(id);
        return result > 0;
    }

    /**
     * 密码加密方法
     */
    private String encryptPassword(String password) {
        // 使用MD5加密，实际项目建议使用更安全的加密方式
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }
}